const Base = require('./base.js');

module.exports = class extends Base {

  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const list = await this.model('dict').page(page, size).countSelect();
    return this.success(list);
  }

  async itemAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;
    const dictId = this.get('dictId');

    const model = this.model('dict_item');
    const data = await model.where({dictId: dictId}).order(['sort ASC']).page(page, size).countSelect();
    return this.success(data);
  }

  async itemPutAction(){
    const values = this.post();
    const id = this.post('id');
    const model = this.model('dict_item');

    if (id > 0) {
      values.updateTime = ['exp', 'CURRENT_TIMESTAMP()']
      await model.where({id: id}).update(values);
    } else {
      delete values.id;
      values.createTime = ['exp', 'CURRENT_TIMESTAMP()']
      await model.add(values);
    }
    return this.success(values);
  }

  async putAction() {

    const values = this.post();
    const id = this.post('id');
    const model = this.model('dict');

    if (id > 0) {
      values.update_time = ['exp', 'CURRENT_TIMESTAMP()']
      await model.where({id: id}).update(values);
    } else {
      delete values.id;
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()']
      await model.add(values);
    }
    return this.success(values);
  }

  async deleteAction() {
    const id = this.get('id');
    await this.model('dict').where({id: id}).limit(1).delete();

    return this.success();
  }

  async itemDeltetAction() {
    const id = this.get('id');
    await this.model('dict_item').where({id: id}).limit(1).delete();

    return this.success();
  }

  
  async findAction(){
    const type = this.get('type');
    const data = await this.model('dict_item').where({type: type}).select();
    return this.success(data);
  }
};
